/**
 * @Description:
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 05/05/25 PM8:29
 */

import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { Response, Request } from 'express';
import { ResultData } from '@/common/utils/result-data';
import { isString } from 'sf-utils2';
import { ValidationError } from 'class-validator';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost): any {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    let status: number;
    let errorResponse: string | object;

    // 这里需要判断错误响应是否是数组，并进行相应处理
    let errorMessage: string;

    if (exception instanceof ValidationError) {
      // 如果是验证错误，则提取第一个错误信息
      // 提取第一个错误信息
      // eslint-disable-next-line @typescript-eslint/no-base-to-string
      errorMessage = exception.constraints ? Object.values(exception?.constraints || []).join('、') : '参数校验失败';
    } else if (exception instanceof HttpException) {
      status = exception.getStatus();
      errorResponse = exception.getResponse();
    } else {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      errorResponse = exception;
    }

    if (!errorMessage) {
      // 普通对象
      if (typeof errorResponse === 'object' && errorResponse !== null && 'message' in errorResponse) {
        errorMessage = Array.isArray(errorResponse.message)
          ? errorResponse.message?.join?.('、')
          : (errorResponse.message as string);
      } else if (isString(errorMessage)) {
        errorMessage = errorResponse as string;
      }
    }

    errorMessage ||= '服务异常';
    const errorJson = ResultData.err(errorMessage);
    errorJson.responseId = request.params._responseId;

    // HttpStatus.OK
    return response.status(status).json({
      ...errorJson,
      path: request.url,
    });
  }
}
